//
//  YWPengyouquanController.m
//  YueshengToutiao
//
//  Created by jun peng on 2022/5/22.
//  Copyright © 2022 YW. All rights reserved.
//

#import "YWPengyouquanController.h"

#import "YWLittleVideoDetailController.h"

#import "YWRequestHeaderParam.h"
#import "YWRequestHeaderStatus.h"
#import "YWRequestHeaderResultStatus.h"
#import "YWRequestHeaderTool.h"

#import "YWGetNewsListParam.h"
#import "YWGetNewsListStatus.h"
#import "YWGetNewsResultStatus.h"
#import "YWGetNewsDataStatus.h"
#import "YWGetNewsTool3.h"
#import "YWListCellDelegate.h"

#import "YWHomeInfoCell.h"
#import "YWHomeRecommendVedioCell.h"
#import "YWHomeRecommendLittleVedioCell.h"
#import "YWHomeRecommendLiveCell.h"

#import "YWVideoView.h"

#import "YWVideoBrowserAnimator.h"

#import "YWHengVideoDetailController.h"
#import "YWHengAnimationVedioView.h"

#import "YWPhotoBrowserAnimator.h"
#import "YWPhototBrowserController.h"
#import "YWNavigationController.h"

@interface YWPengyouquanController ()<UITableViewDelegate,UITableViewDataSource,YWListCellDelegate,YWVideoViewDelegate,YWVideoBrowserAnimatorPresentedDelegate,YWLittleVideoDetailControllerDelegate/*,YWHengVideoDetailControllerDelegate*/,YWPhotoBrowserAnimatorPresentedDelegate,YWPhotoBrowserAnimatorDismissDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barConstraintHeight;
@property (weak, nonatomic) IBOutlet YWTableView *tableView;

@property(nonatomic,strong)NSMutableArray *statusArray;
@property (nonatomic,assign)NSInteger page;

@property (nonatomic, strong) UIView * vedioBgView; // 播放器BgView
@property (nonatomic, strong) YWVideoView * vedioView; // 播放器

@property (weak, nonatomic) IBOutlet UIView *bgView;

//转场动画
@property(nonatomic,strong)YWVideoBrowserAnimator *animator;

@property(nonatomic,weak)UIButton *rightItem;

@property(nonatomic,strong)UIView *hengBgWhiteView;
@property(nonatomic,strong)YWHengAnimationVedioView *hengAnimationVedioView;

@property(nonatomic,assign)BOOL isGoToHengVideoDetailVCToDisAppearView;
@property(nonatomic,assign)BOOL isShowingLittleVedioVC;

//转场动画
@property(nonatomic,strong)YWPhotoBrowserAnimator *animator2;

@end

@implementation YWPengyouquanController

#pragma mark - 懒加载
-(YWPhotoBrowserAnimator *)animator2{
    if (_animator2 == nil) {
        _animator2 = [[YWPhotoBrowserAnimator alloc] init];
    }
    return _animator2;
}


-(UIView *)hengBgWhiteView{
    if (_hengBgWhiteView == nil) {
        
        _hengBgWhiteView = [[UIView alloc] init];
        _hengBgWhiteView.frame = CGRectMake(0, 0, Wi, He);
        
        _hengBgWhiteView.backgroundColor = [UIColor whiteColor];
        _hengBgWhiteView.alpha = 0;
    }
    return _hengBgWhiteView;
}

-(YWHengAnimationVedioView *)hengAnimationVedioView{
    if (_hengAnimationVedioView == nil) {
        _hengAnimationVedioView = [YWHengAnimationVedioView videoView];
        
        _hengAnimationVedioView.backgroundColor = [UIColor blackColor];
    }
    return _hengAnimationVedioView;
}


#pragma mark - 懒加载
-(YWVideoBrowserAnimator *)animator{
    if (_animator == nil) {
        _animator = [[YWVideoBrowserAnimator alloc] init];
    }
    return _animator;
}

////从横详情视频VC回来的动画效果
//-(void)hengVideoDetailControllerDidPopVC:(YWHengVideoDetailController *)vc{
//
//
//}

//去横视频详情VC或者竖视频VC
-(void)videoViewDidTap:(YWVideoView *)videoView{
    
    YWGetNewsDataStatus *status = [self.statusArray objectAtIndex:videoView.index];
    
    if (status.cellType == YWCellTypeVideo){
        
        //是不是因为去横视频详情VC而离开本界面
        self.isGoToHengVideoDetailVCToDisAppearView = YES;
        
        //1、hengAnimationVedioView开始播放/继续播放
        [self.hengAnimationVedioView continuePlayWithAnthorViewWithUrl:status.FileUrl WithMute:NO];
        
        //2、添加
        [[UIApplication sharedApplication].keyWindow addSubview:self.hengBgWhiteView];
        [[UIApplication sharedApplication].keyWindow addSubview:self.hengAnimationVedioView];
        
        //3、初始化位置
        CGRect startRect = [self.tableView convertRect:self.vedioBgView.frame toView:[UIApplication sharedApplication].keyWindow];
        
        self.hengAnimationVedioView.frame = startRect;
        
        //4、动画
        [UIView animateWithDuration:0.3 animations:^{
            
            self.hengBgWhiteView.alpha = 1;
            self.hengAnimationVedioView.frame = CGRectMake(0, self.navBar.height, Wi, headerViewVedioViewHeight);
        }completion:^(BOOL finished) {
            
            //5、弹出新的VC
            YWHengVideoDetailController *vc = [[YWHengVideoDetailController alloc] initWithNibName:@"YWHengVideoDetailController" bundle:nil];
//            vc.delegate = self;
            vc.status = status;
            
            [self.navigationController pushViewController:vc animated:NO];
            
            //6、移除动画view
            self.hengBgWhiteView.alpha = 0;
            [self.hengAnimationVedioView removeFromSuperview];
            [self.hengBgWhiteView removeFromSuperview];
            
            
        }];
        
        
       
    }
    else if (status.cellType == YWCellTypeLittleVideo){
        
        NSIndexPath *contentBeginIndexPath = [NSIndexPath indexPathForRow:videoView.index inSection:0];
        
        //这里就是直接去详情了
        // 1.创建控制器
        YWLittleVideoDetailController *vc = [[YWLittleVideoDetailController alloc] initWithNibName:@"YWLittleVideoDetailController" bundle:nil];
        
        vc.FileUrl = videoView.urlString;
        
        // 2.设置modal样式
        vc.modalPresentationStyle = UIModalPresentationCustom;
        
        // 3.设置转场的代理
        vc.transitioningDelegate = (id<UIViewControllerTransitioningDelegate>)self.animator;
        vc.delegate = self;
        
        //不要创建一个新player、用回旧的然后add在新view
        vc.isAddAnotherViewToContinuePlay = YES;
        
        // 4.设置动画的代理
        self.animator.presentedDelegate = self;
        self.animator.contentBeginIndexPath = contentBeginIndexPath;
        self.animator.dismissDelegate = (id<YWVideoBrowserAnimatorDismissDelegate>)vc;

        // 以modal的形式弹出控制器
        [self presentViewController:vc animated:YES completion:nil];
        
        self.isShowingLittleVedioVC = YES;
    }
    
    
    
  
}

//去横视频详情VC
-(void)listCell:(id)listCell didClickPlayVideoWithDataStatus:(YWGetNewsDataStatus *)status{
    
    //是不是因为去横视频详情VC而离开本界面
    self.isGoToHengVideoDetailVCToDisAppearView = YES;
    
    //1、hengAnimationVedioView开始播放/继续播放
    if (self.vedioView.isPlaying == YES && self.vedioView.index == [self.statusArray indexOfObject:status]) {
        [self.hengAnimationVedioView continuePlayWithAnthorViewWithUrl:status.FileUrl WithMute:NO];
    }
    else{
        
        [self.hengAnimationVedioView startPlayWithUrl:status.FileUrl withMute:NO];
    }
    
    //2、添加
    [[UIApplication sharedApplication].keyWindow addSubview:self.hengBgWhiteView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.hengAnimationVedioView];
    
    //3、初始化位置
    YWHomeRecommendVedioCell *videoCell = (YWHomeRecommendVedioCell *)listCell;
    
    CGRect startRect = [videoCell.contentView convertRect:videoCell.videoBgView.frame toView:[UIApplication sharedApplication].keyWindow];
    
    self.hengAnimationVedioView.frame = startRect;
    
    //4、动画
    [UIView animateWithDuration:0.3 animations:^{
        
        self.hengBgWhiteView.alpha = 1;
        self.hengAnimationVedioView.frame = CGRectMake(0, self.navBar.height, Wi, headerViewVedioViewHeight);
    }completion:^(BOOL finished) {
        
        //5、弹出新的VC
        YWHengVideoDetailController *vc = [[YWHengVideoDetailController alloc] initWithNibName:@"YWHengVideoDetailController" bundle:nil];
//        vc.delegate = self;
        vc.status = status;
        
        [self.navigationController pushViewController:vc animated:NO];
        
        //6、移除动画view
        self.hengBgWhiteView.alpha = 0;
        [self.hengAnimationVedioView removeFromSuperview];
        [self.hengBgWhiteView removeFromSuperview];
        
        
    }];
    
    
   
    //5、这个index也先保存、到时朋友圈DetailVC dismiss的时候的代理方法里就可以用到了
    self.vedioView.index = [self.statusArray indexOfObject:status];
    
    
    
    /*
     
    NSIndexPath *contentBeginIndexPath = [NSIndexPath indexPathForRow:[self.statusArray indexOfObject:status] inSection:0];
    
    //这里就是直接去详情了
    // 1.创建控制器
    YWLittleVideoDetailController *vc = [[YWLittleVideoDetailController alloc] initWithNibName:@"YWLittleVideoDetailController" bundle:nil];
    
    vc.FileUrl = status.FileUrl;
    
    // 2.设置modal样式
    vc.modalPresentationStyle = UIModalPresentationCustom;
    
    // 3.设置转场的代理
    vc.transitioningDelegate = (id<UIViewControllerTransitioningDelegate>)self.animator;
    vc.delegate = self;
    
    // 4.设置动画的代理
    self.animator.presentedDelegate = self;
    self.animator.contentBeginIndexPath = contentBeginIndexPath;
    self.animator.dismissDelegate = (id<YWVideoBrowserAnimatorDismissDelegate>)vc;

    // 以modal的形式弹出控制器
    [self presentViewController:vc animated:YES completion:nil];
    
    //这个index也先保存、到时朋友圈DetailVC dismiss的时候的代理方法里就可以用到了
    self.vedioView.index = [self.statusArray indexOfObject:status];
    */
    
    /*
     //这里一开始做成了不去详情VC而是去做成播放
//    YWHomeRecommendVedioCell *videoCell = (YWHomeRecommendVedioCell *)listCell;
//
//        NSIndexPath *indexPath = [self.tableView indexPathForCell:videoCell];
//
//        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
//
//    //转换父控件所在位置
//    CGRect rects = [videoCell.contentView convertRect:videoCell.videoBgView.frame toView:self.tableView];
//
//    self.vedioBgView.frame = rects;
//
//    self.vedioView.frame = self.vedioBgView.bounds;
//
//    self.vedioView.index = [self.statusArray indexOfObject:status];
//
//    [self.vedioView startPlayWithUrl:status.FileUrl withMute:YES];
//
//    self.vedioBgView.hidden = NO;
//
//self.vedioBgView.layer.cornerRadius = videoCell.videoBgView.layer.cornerRadius;
//self.vedioBgView.clipsToBounds = YES;
    
    */
    
}

//去竖视频详情VC
-(void)listCell:(id)listCell didClickPlayLittleVideoWithDataStatus:(YWGetNewsDataStatus *)status{
    
//        [self.vedioView stopPlay];
//        self.vedioBgView.hidden = YES;
    
    NSIndexPath *contentBeginIndexPath = [NSIndexPath indexPathForRow:[self.statusArray indexOfObject:status] inSection:0];
    
    //这里就是直接去详情了
    // 1.创建控制器
    YWLittleVideoDetailController *vc = [[YWLittleVideoDetailController alloc] initWithNibName:@"YWLittleVideoDetailController" bundle:nil];
    
    vc.FileUrl = status.FileUrl;
    
    // 2.设置modal样式
    vc.modalPresentationStyle = UIModalPresentationCustom;
    
    // 3.设置转场的代理
    vc.transitioningDelegate = (id<UIViewControllerTransitioningDelegate>)self.animator;
    vc.delegate = self;
    
    // 4.设置动画的代理
    self.animator.presentedDelegate = self;
    self.animator.contentBeginIndexPath = contentBeginIndexPath;
    self.animator.dismissDelegate = (id<YWVideoBrowserAnimatorDismissDelegate>)vc;

    // 以modal的形式弹出控制器
    [self presentViewController:vc animated:YES completion:nil];
    
    self.isShowingLittleVedioVC = YES;
    
    //这个index也先保存、到时朋友圈DetailVC dismiss的时候的代理方法里就可以用到了
    self.vedioView.index = [self.statusArray indexOfObject:status];
    
    //这里一开始做成了不去详情VC而是去做成播放
//    YWHomeRecommendLittleVedioCell *videoCell = (YWHomeRecommendLittleVedioCell *)listCell;
//
//        NSIndexPath *indexPath = [self.tableView indexPathForCell:videoCell];
//
//        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
//
//    //转换父控件所在位置
//    CGRect rects = [videoCell.contentView convertRect:videoCell.videoBgView.frame toView:self.tableView];
//
//    self.vedioBgView.frame = rects;
//
//    self.vedioView.frame = self.vedioBgView.bounds;
//
//    self.vedioView.index = [self.statusArray indexOfObject:status];
//
//    [self.vedioView startPlayWithUrl:status.FileUrl withMute:YES];
//
//    self.vedioBgView.hidden = NO;
//
//self.vedioBgView.layer.cornerRadius = videoCell.videoBgView.layer.cornerRadius;
//self.vedioBgView.clipsToBounds = YES;

}

#pragma mark - YWPhotoBrowserAnimatorPresentedDelegate
//11期的开始代理是cell里的collectionView完成的、现在我这里交给VC完成、因为11期是collectionView触发、我这里是tableView触发
-(CGRect)startRect:(NSIndexPath *)contentBeginIndexPath{
    
    id cell = [self.tableView cellForRowAtIndexPath:contentBeginIndexPath];
    
    if ([cell isKindOfClass:[YWHomeRecommendVedioCell class]]) {
        YWHomeRecommendVedioCell *videoCell = (YWHomeRecommendVedioCell *)cell;
        
        // 获取图片的frame
        CGRect startRect = [videoCell.contentView convertRect:videoCell.videoBgView.frame toView:[UIApplication sharedApplication].keyWindow];
        
        return startRect;
    }
    else if ([cell isKindOfClass:[YWHomeRecommendLittleVedioCell class]]) {
        YWHomeRecommendLittleVedioCell *videoCell = (YWHomeRecommendLittleVedioCell *)cell;
        
        // 获取图片的frame
        CGRect startRect = [videoCell.contentView convertRect:videoCell.videoBgView.frame toView:[UIApplication sharedApplication].keyWindow];
        
        return startRect;
    }
    else{
        return CGRectZero;
    }
    
}

-(CGRect)endRect:(NSIndexPath *)contentBeginIndexPath{

    // 1.获取该位置的image的size
//    YWChatStatusFrame2 *statusFrame = self.chatMsgs[contentBeginIndexPath.row];
//    YWChatStatus3 *status = statusFrame.status3;
//    EMMessage *message = status.message;
//    EMImageMessageBody *imageContent = (EMImageMessageBody*)(message.body);
//    CGSize size = imageContent.size;
//
//    // 2.计算结束后的frame
//    CGFloat w = Wi;
//    CGFloat h = w / size.width * size.height;
//    CGFloat y = 0;
//    if (h>He) {
//        y = 0;
//    }
//    else{
//        y = (He - h) * 0.5;
//    }

    return CGRectMake(0, 0, Wi, He);

}

-(UIImageView *)imageView:(NSIndexPath *)contentBeginIndexPath{
    
    // 1.创建UIImageView对象
    UIImageView *imageView = [[UIImageView alloc] init];
    
    imageView.backgroundColor = [UIColor clearColor];
    
    if (self.vedioView.isPlaying && self.vedioView.index == contentBeginIndexPath.row) {
        [self.vedioView snapshot:^(UIImage * _Nonnull image) {
            imageView.image = image;
        }];
    }
    else{
        

         id cell = [self.tableView cellForRowAtIndexPath:contentBeginIndexPath];
        
        if ([cell isKindOfClass:[YWHomeRecommendVedioCell class]]) {
            YWHomeRecommendVedioCell *videoCell = (YWHomeRecommendVedioCell *)cell;
            
            imageView.image = videoCell.iconView.image;
            
        }
        else if ([cell isKindOfClass:[YWHomeRecommendLittleVedioCell class]]) {
            YWHomeRecommendLittleVedioCell *videoCell = (YWHomeRecommendLittleVedioCell *)cell;
            
            imageView.image = videoCell.iconView.image;
            
        }
        
    }
    
    
    // 3.设置imageView的属性
    imageView.contentMode = UIViewContentModeScaleAspectFit;
//    imageView.clipsToBounds = YES;

    return imageView;
}


//用自定义present弹出VC是不走这viewWillDisappear方法
//离开此页面要停止播放
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    //这个无论是不是去横视频界面都去隐藏vedioBgView
    self.vedioBgView.hidden = YES;
    
    //假如是因为去横视频详情而离开本界面的不要去停止vedioView
    if (self.isGoToHengVideoDetailVCToDisAppearView) {
        return;
    }
    
     [self.vedioView stopPlay];
    
}


//用自定义present弹出VC是不走这viewWillAppear方法
//重新出现的时候，videoView更加精准找到自己位置
-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    if (self.isGoToHengVideoDetailVCToDisAppearView == YES) {
        
        //这里就用这个吧、因为有可能列表有两个横视频，但是scrollToStartPlay是按顺序可能会播放第一个，其实我想播放的是第二个
        [self popVCToContinuePlayHengVideoView];
        
    }
    else{
        
         [self scrollToStartPlay:self.tableView];
        
    }
    
    
     self.isGoToHengVideoDetailVCToDisAppearView = NO;
}

//从横视频详情VC回来调用的继续播放方法
-(void)popVCToContinuePlayHengVideoView{
    
    YWGetNewsDataStatus *status = self.statusArray[self.vedioView.index];
    
    
//    if (self.vedioView.isPlaying == YES) {
//
//        [self.vedioView continuePlayWithAnthorViewWithUrl:status.FileUrl WithMute:YES];
//    }
//    else{ //按理这里一定是走这里、因为从横视频回来前视频被stop了、因为横视频详情的子VC播放的视频可能和列表的不一致（要么就只能在横视频viewDidDisappear里代理传值URL过啦判断是否和status.FileUrl是否一样、一样就continuePlay、不一样就startPlay）、所以我不能pause再continue、怕URL不一样、所以我这里先stop再start了<它这个SDK用start会等停顿一下才播放的、用continue才会无缝衔接播放>
        [self.vedioView startPlayWithUrl:status.FileUrl withMute:YES];
//    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.vedioView.index inSection:0];
    
    id cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    
    if ([cell isKindOfClass:[YWHomeRecommendVedioCell class]]) {
        
        YWHomeRecommendVedioCell *vedioCell = (YWHomeRecommendVedioCell *)cell;
           
        //转换父控件所在位置
        CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

        self.vedioBgView.frame = rects;

        self.vedioView.frame = self.vedioBgView.bounds;

        self.vedioBgView.layer.cornerRadius = vedioCell.videoBgView.layer.cornerRadius;
        self.vedioBgView.clipsToBounds = YES;

        
        self.vedioBgView.hidden = NO;
   
    }
    
    [self getFileSize];
    
}

//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    [self scrollToStartPlay:self.tableView];
//    
//}

//littleVideoDetailController退出dismiss的时候调用
-(void)littleVideoDetailControllerDidDismissVC:(YWLittleVideoDetailController *)vc{
  
    self.isShowingLittleVedioVC = NO;
    
    //去其它view继续播放，不要先停止之前正在播放的、而是继续播放
    [self.vedioView continuePlayWithAnthorViewWithUrl:vc.FileUrl WithMute:YES];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.vedioView.index inSection:0];
    
    id cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    
    if ([cell isKindOfClass:[YWHomeRecommendVedioCell class]]) {
        
        YWHomeRecommendVedioCell *vedioCell = (YWHomeRecommendVedioCell *)cell;
           
        //转换父控件所在位置
        CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

        self.vedioBgView.frame = rects;

        self.vedioView.frame = self.vedioBgView.bounds;

        self.vedioBgView.layer.cornerRadius = vedioCell.videoBgView.layer.cornerRadius;
        self.vedioBgView.clipsToBounds = YES;

        
        self.vedioBgView.hidden = NO;

    }
    else  if ([cell isKindOfClass:[YWHomeRecommendLittleVedioCell class]]) {
        
        YWHomeRecommendLittleVedioCell *vedioCell = (YWHomeRecommendLittleVedioCell *)cell;
         
        //转换父控件所在位置
        CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

        self.vedioBgView.frame = rects;

        self.vedioView.frame = self.vedioBgView.bounds;

        self.vedioBgView.layer.cornerRadius = vedioCell.videoBgView.layer.cornerRadius;
        self.vedioBgView.clipsToBounds = YES;

        
        self.vedioBgView.hidden = NO;

    }
    
    //获取存储大小
    [self getFileSize];
}

//滚动过程中看哪视频需要停止播放
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    
    if(self.vedioView.isPlaying == YES)
    {
         //正在播放状态

            NSInteger index = self.vedioView.index;
            
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            
            id cell = [self.tableView cellForRowAtIndexPath:indexPath];
            
        YWLog(@"%@",[cell class]);
        
        
        //点击更多、是重新刷新的过程、由于有些文章太长、导致下面的本来正在播放视频cell已经超出了屏幕的可是范围，而根据indexPath拿回之前的视频cell是null的（reloadData之后cell还没有创建出来、要第一次见到cell、cell才会被创建），所以要写下面的两步、避免出现vedioView在长文章上面
        if ([cell isKindOfClass:[NSNull class]] || cell == nil) {
            
            [self.vedioView stopPlay];
            self.vedioBgView.hidden = YES;
            
            
            return;
        }
        
        if ([cell isKindOfClass:[YWHomeRecommendVedioCell class]]) {
            YWHomeRecommendVedioCell *vedioCell = (YWHomeRecommendVedioCell *)cell;
            
//其实这里重新赋值rect可能不需要、因为本来就是add在了tableView上
            //转换父控件所在位置
            CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

            //不断改变vedioBgView位置
            self.vedioBgView.frame = rects;

            self.vedioView.frame = self.vedioBgView.bounds;

            YWLog(@"rects：%@",NSStringFromCGRect(rects));
            
        //    判断播放视频的cell是否离开了屏幕
            CGRect cellRect = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.bgView];
            
            if ((cellRect.origin.y < -cellRect.size.height) || (cellRect.origin.y > self.bgView.height)) {
                [self.vedioView stopPlay];
                self.vedioBgView.hidden = YES;
            }
            
            YWLog(@"%@",NSStringFromCGRect(cellRect));

        }
        else  if ([cell isKindOfClass:[YWHomeRecommendLittleVedioCell class]]) {
            YWHomeRecommendLittleVedioCell *vedioCell = (YWHomeRecommendLittleVedioCell *)cell;
            
//其实这里重新赋值rect可能不需要、因为本来就是add在了tableView上
            //转换父控件所在位置
            CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

            //不断改变vedioBgView位置
            self.vedioBgView.frame = rects;

            self.vedioView.frame = self.vedioBgView.bounds;

            YWLog(@"rects：%@",NSStringFromCGRect(rects));
            
        //    判断播放视频的cell是否离开了屏幕
            CGRect cellRect = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.bgView];
            
            if ((cellRect.origin.y < -cellRect.size.height) || (cellRect.origin.y > self.bgView.height)) {
                [self.vedioView stopPlay];
                self.vedioBgView.hidden = YES;
            }
            
            YWLog(@"%@",NSStringFromCGRect(cellRect));

        }
        
    }
   
    
}




-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
//    [self scrollToStartPlay:scrollView];
    
    if (decelerate == YES) {
        
//        [self scrollToStartPlay:scrollView]; //这个和下面的减速可能冲突会出现滚动播放卡顿所以这个不要
    }
    else{
        
        [self scrollToStartPlay:scrollView];
    }
    
    
    YWLog(@"aaa:scrollViewDidEndDragging");
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    [self scrollToStartPlay:scrollView];
    
    YWLog(@"aaa:scrollViewDidEndDecelerating");
    
}

//滚动过程中寻找可播放的cell
-(void)scrollToStartPlay:(UIScrollView *)scrollView{
    if(self.vedioView.isPlaying == NO)  {
        
//          暂停播放状态/没有播放状态
//        遍历可见到的cell，假如是视频的就直接播放，获取到第一个视频cell就记得要return

        NSArray *cellArray = [self.tableView visibleCells];
        
        YWLog(@"cellArray_count:%ld",cellArray.count);

          for (id cell in cellArray) {
              
              //小视频才自动播放、大视频太大了你自动播放就会下载到沙盒就会很费内存和流量了
              if ([cell isKindOfClass:[YWHomeRecommendLittleVedioCell class]]) {
                  YWHomeRecommendLittleVedioCell *vedioCell = (YWHomeRecommendLittleVedioCell *)cell;
                      NSIndexPath *indexPath = [self.tableView indexPathForCell:vedioCell];

                  
                  //播放器中心距离bgView中心在一定距离才能播放
                  CGRect cellRect = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.bgView];
                  
                  CGFloat videoCenterY = cellRect.origin.y + cellRect.size.height/2;
                  CGFloat bgViewCenterY = self.bgView.height/2;
                  
                  CGFloat absY = fabs(videoCenterY - bgViewCenterY);
                  
                  //absY > fabs(bgViewCenterY - cellRect.size.height/2这个意思是整个videoView都要露出来才播放
                  if (absY > fabs(bgViewCenterY - cellRect.size.height/2)) { //假如距离太远就寻找下一个播放器
                      continue;
                  }
                  
                  
                  

                  //转换父控件所在位置
                  CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

                  self.vedioBgView.frame = rects;

                  self.vedioView.frame = self.vedioBgView.bounds;

                  self.vedioView.index = indexPath.row;

                  YWGetNewsDataStatus *vedioStatus = self.statusArray[indexPath.row];

                  //这里按理mute是YES、但是这里先测试设置NO
                  [self.vedioView startPlayWithUrl:vedioStatus.FileUrl withMute:YES];

                  self.vedioBgView.layer.cornerRadius = vedioCell.videoBgView.layer.cornerRadius;
                  self.vedioBgView.clipsToBounds = YES;

                   //GCD延迟
                  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                             self.vedioBgView.hidden = NO;
                      });



                  break;;
              }
             //假如你要做从横视频回来可以播放横视频的话就要写下面的了
             else if ([cell isKindOfClass:[YWHomeRecommendVedioCell class]]) {
                  YWHomeRecommendVedioCell *vedioCell = (YWHomeRecommendVedioCell *)cell;
                      NSIndexPath *indexPath = [self.tableView indexPathForCell:vedioCell];


                  //播放器中心距离bgView中心在一定距离才能播放
                  CGRect cellRect = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.bgView];
                  
                  CGFloat videoCenterY = cellRect.origin.y + cellRect.size.height/2;
                  CGFloat bgViewCenterY = self.bgView.height/2;
                  
                  CGFloat absY = fabs(videoCenterY - bgViewCenterY);
                  
                  //absY > fabs(bgViewCenterY - cellRect.size.height/2这个意思是整个videoView都要露出来才播放
                  if (absY > fabs(bgViewCenterY - cellRect.size.height/2)) { //假如距离太远就寻找下一个播放器
                      continue;
                  }
                  
                  
                  //转换父控件所在位置
                  CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

                  self.vedioBgView.frame = rects;

                  self.vedioView.frame = self.vedioBgView.bounds;

                  self.vedioView.index = indexPath.row;

                  YWGetNewsDataStatus *vedioStatus = self.statusArray[indexPath.row];

//这里按理mute是YES、但是这里先测试设置NO
                  [self.vedioView startPlayWithUrl:vedioStatus.FileUrl withMute:YES];

                  self.vedioBgView.layer.cornerRadius = vedioCell.videoBgView.layer.cornerRadius;
                  self.vedioBgView.clipsToBounds = YES;

                   //GCD延迟
                  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                             self.vedioBgView.hidden = NO;
                      });



                  break;
              }
                
          }

    }
    
    //获取存储大小
    [self getFileSize];
}



-(NSMutableArray *)statusArray{
    if (_statusArray == nil) {
        _statusArray = [NSMutableArray array];
    }
    return _statusArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navBar.title = @"朋友圈";
    self.barConstraintHeight.constant = self.navBar.frame.size.height;
    
    [self loadRequestHeaderData];
    
    // 创建播放器
        self.vedioView = [YWVideoView videoView];
        self.vedioView.delegate = self;
    
        self.vedioBgView = [UIView new];
        [self.tableView addSubview:self.vedioBgView];
        self.vedioBgView.backgroundColor = [UIColor blackColor];
        self.vedioView.backgroundColor = [UIColor blackColor];
        self.vedioBgView.hidden = YES;
    
        [self.vedioBgView addSubview:self.vedioView];
    
        self.vedioView.frame = self.vedioBgView.bounds;
    
    [self setupRightItem];
    
    [self setupLeftItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPhotoBrowser:) name:ShowPhotoBrowserNote object:nil];
    
    //点击状态栏不会回到最上面、这样防止正在播放小视频详情VC的时候（因为小视频详情VC事用custom来present出来的、所以点击状态栏朋友圈VC也会受到影响）
    self.tableView.scrollsToTop = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForeground) name:YWEnterForegroundNote object:nil];
    
}

-(void)enterForeground{
   
    YWNavigationController *nav = self.tabBarController.selectedViewController;
    if (nav.topViewController == self) {
//        if (self.presentingViewController) {
//            return;
//        }
        if (self.isShowingLittleVedioVC == YES) { //假如正在播放小视频的就不走下面的
            return;
        }
         [self scrollToStartPlay:self.tableView];
    }
    
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

-(void)showPhotoBrowser:(NSNotification *)notification{
    
    //因为通知有一对多、所以要增加一个判断防止和其它VC同时接收
    YWNavigationController *nav = self.tabBarController.selectedViewController;
    if (nav.topViewController != self) {
        return;
    }
    
//
    
    NSDictionary *userInfo = notification.userInfo;
    
    NSIndexPath *indexPath = userInfo[ShowPhotoBrowserIndexKey];
    
    NSArray *iconStatusArray = userInfo[ShowPhotoBrowserUrlsKey];
    
    id object = notification.object;
    
    YWPhototBrowserController *vc = [[YWPhototBrowserController alloc] initWithImgBeginIndexPath:indexPath picUrlArray:iconStatusArray];
    
    // 2.设置modal样式
    vc.modalPresentationStyle = UIModalPresentationCustom;
    
    // 3.设置转场的代理
    vc.transitioningDelegate = (id<UIViewControllerTransitioningDelegate>)self.animator2;
  
    
    // 4.设置动画的代理
    self.animator2.presentedDelegate = object;
    self.animator2.indexPath = indexPath;
    self.animator2.dismissDelegate = (id<YWPhotoBrowserAnimatorDismissDelegate>)vc;

    // 以modal的形式弹出控制器
    [self presentViewController:vc animated:YES completion:nil];
    
    
}



//建立左边的item
-(void)setupLeftItem{
    
    UIButton *backBtn = [[UIButton alloc] init];
    [backBtn setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateHighlighted];
    backBtn.bounds = CGRectMake(0, 0, 100, 30);
    self.navBar.leftItem = backBtn;
    [backBtn addTarget:self action:@selector(askShow) forControlEvents:UIControlEventTouchUpInside];
    
    [backBtn setTitle:@"提示" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [backBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 0)];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
}

-(void)askShow{
    
    YWAskView *askView = [YWAskView askView];
    
    askView.title = @"1、列表提前“网络预加载”每个视频10M这样你播放下一个视频就不需要等直接可以看了\n\n2、当真正播放视频的时候会自动把视频缓存“下载到沙盒”\n\n3、并且缓存到沙盒的视频就算你只是缓存了一半（包括你关闭app重新打开且没有网络的情况下）也能观看\n\n4、播放一个视频然后停止播放它、它就不会继续下载视频到沙盒了、只有播放期间才会下载视频到沙盒\n\n5、当视频缓存达到超过300M将会自动清理缓存\n\n6、整个播放逻辑用到了单例Manager、且Manager只会拥有一个播放器player、而信息模型是装在Manager的字典里、videoView作为每个VC的界面独立存在这个就不应该是单例\n\n7、播放器就只有一个而这个播放器在播放途中你想在哪个界面播放就哪个界面播放可以不暂停来转移界面播放\n\n8、这里是scrollView滚到有小视频的地方都会自动播放\n\n9、点击小视频会用到自定义present效果且去另一个界面不用暂停地继续播放";
    [askView show];
    
}

-(void)setupRightItem{
    
    UIButton *rightItem = [[UIButton alloc] init];
    self.rightItem = rightItem;
    [rightItem setTitle:@"清理缓存" forState:UIControlStateNormal];
    [rightItem setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [followBtn setImage:[UIImage imageNamed:@"消息关注"] forState:UIControlStateNormal];
    //    self.navBar.navBarTintColor = otherMainColor;
    rightItem.bounds = CGRectMake(0, 0, 180, 44);
    rightItem.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    //    locationBtn.imagei = UIEdgeInsetsMake(0, -10, 0, 0);
//    [followBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 13)];
    [rightItem setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 8)];
    self.navBar.rightItem = rightItem;
    rightItem.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightItem addTarget:self action:@selector(clean_disk) forControlEvents:UIControlEventTouchUpInside];
}

//清理缓存
-(void)clean_disk{
    
    [XMGFileTool removeDirectoryPath:YWVideoCachepath];

    [self getFileSize];
    
    
}



-(void)getFileSize{
    
    // 获取文件夹尺寸
    // 文件夹非常小,如果我的文件非常大
    [XMGFileTool getFileSize:YWVideoCachepath completion:^(NSInteger totalSize) {
        
        if (totalSize > 300 * 1000 * 1000) {
            
            [XMGFileTool removeDirectoryPath:YWVideoCachepath];
            
            totalSize = 0;
        }
        
    [self.rightItem setTitle:[self sizeStr:totalSize] forState:UIControlStateNormal];
    }];
}

// 获取缓存尺寸字符串
- (NSString *)sizeStr:(NSInteger)totalSize
{
    
   NSString *sizeStr = @"清除缓存";
   // MB KB B
   if (totalSize > 1000 * 1000) {
       // MB
       CGFloat sizeF = totalSize / 1000.0 / 1000.0;
       sizeStr = [NSString stringWithFormat:@"%@(%.1fMB)",sizeStr,sizeF];
   } else if (totalSize > 1000) {
       // KB
       CGFloat sizeF = totalSize / 1000.0;
       sizeStr = [NSString stringWithFormat:@"%@(%.1fKB)",sizeStr,sizeF];
   } else if (totalSize > 0) {
       // B
       sizeStr = [NSString stringWithFormat:@"%@(%.ldB)",sizeStr,totalSize];
   }
   else{
       
       sizeStr = [NSString stringWithFormat:@"%@(0B)",sizeStr];
   }

   return sizeStr;
}

//调用请求头接口
-(void)loadRequestHeaderData{
    
    //本地没有access_token就是第一次下载的
       NSUserDefaults *defaults2 =[NSUserDefaults standardUserDefaults];
       
       NSString *access_token = [defaults2 objectForKey:accessTokenStr];
    
    //第一次下载app的才需要showMessage
    if (access_token == nil) {
        
        [MBProgressHUD showMessage:nil toView:self.view];
    }
    
    //这里用keywindow防止还没有加载完这个接口用户就点击其它栏目
//    [MBProgressHUD showMessage:nil toView:self.view];
    
    YWRequestHeaderParam *param = [[YWRequestHeaderParam alloc] init];
    param.username = requestHeaderUserName;
    param.password = requestHeaderPassword;
    
    [YWRequestHeaderTool requestHeaderStatusesWithParameters:param success:^(YWRequestHeaderStatus * _Nonnull status) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        if (status.IsSuccess.integerValue == 1) {
            
            //保存到本地
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            
            [defaults setObject:status.ResultObj.access_token forKey:accessTokenStr];
            [defaults setObject:status.ResultObj.token_type forKey:tokenTypeStr];
            
            [defaults synchronize];
            
            
            MJWeakSelf
            self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

                [weakSelf loadNewsData];

            }];
            
            
            [self.tableView.mj_header beginRefreshing];
            
        }
        else{
            
            [MBProgressHUD showError:status.Message];
            
            
        }
        
    } failure:^(NSError * _Nonnull error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        //不要reloadView，自动重新加载效果应该更好 (现在要回来)
        [self loadRequestHeaderData];
        
    }];
    
}


//加载新数据
-(void)loadNewsData{
    
    self.page = 1;
    YWGetNewsListParam *param = [[YWGetNewsListParam alloc] init];
    param.pagesize = @"20";
    param.currentpage = [NSString stringWithFormat:@"%ld",(long)self.page];
    
    param.type = @"1";
    NSString *userID = self.meStatus.userStatus.Id;
      if (userID != nil) {
           param.userid = userID;
       }
       else{
           
           param.userid = @"";
       }
    
    [YWGetNewsTool3 getNewsListStatusesWithParameters:param success:^(YWGetNewsListStatus * _Nonnull status) {
        
        
               [self.tableView.mj_header endRefreshing];
        
              [self.noContentView removeFromSuperview];
        
        //先停止播放
        [self.vedioView stopPlay];
        
        self.vedioBgView.hidden = YES;
        
        
               if (status.IsSuccess.integerValue == 1) {
                   
                   self.statusArray = [NSMutableArray arrayWithArray:status.ResultObj.PageInfo];
                   
                   
                   [self.tableView reloadData];
                   
                   
                   //预加载
                   NSMutableArray *urlArray = [NSMutableArray array];
                   for (YWGetNewsDataStatus *dataStatus in status.ResultObj.PageInfo) {
                       [urlArray addObject:dataStatus.FileUrl];
                   }
                   YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
                   [playerManager preLoadUrlArray:urlArray];
                   
                   
                   
                   
                   //假如少于就不需要添加上拉控件了
                  if (status.ResultObj.PageInfo.count == param.pagesize.integerValue) {
                   MJWeakSelf
                      //添加上拉刷新控件
                     self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

                         [weakSelf loadMoreData];
                     }];
                      
                   }
                   
                   
                   //再寻找需不需要播放
                   [self scrollToStartPlay:self.tableView];
                   
                   
               }
               else{
                   
                   self.statusArray = [NSMutableArray array];
                   
                   [self.tableView reloadData];
                   
                   
                   [self.view addSubview:self.noContentView];
                   
                   self.noContentView.frame = CGRectMake(0, 0, Wi, self.view.height);
                   
                   self.noContentView.noContentType = YWNoContentView2Type_NoContent;
                   
                   
                   
               }
    } failure:^(NSError * _Nonnull error) {
        
        
        [self.tableView.mj_header endRefreshing];
        
        
        [self.view addSubview:self.noContentView];
        
        self.noContentView.frame = CGRectMake(0, 0, Wi, self.view.height);
        
        self.noContentView.noContentType = YWNoContentView2Type_Error404;
    }];
    
    
}

-(void)noContentView2DidClickRefreshBtn:(YWNoContentView2 *)noContentView2{
    
    [self loadNewsData];
   
    
}

//加载更多
-(void)loadMoreData{
    
    self.page ++;
    YWGetNewsListParam *param = [[YWGetNewsListParam alloc] init];
    param.pagesize = @"20";
    param.currentpage = [NSString stringWithFormat:@"%ld",(long)self.page];
    
    param.type = @"1";
    NSString *userID = self.meStatus.userStatus.Id;
      if (userID != nil) {
           param.userid = userID;
       }
       else{
           
           param.userid = @"";
       }
    [YWGetNewsTool3 getNewsListStatusesWithParameters:param success:^(YWGetNewsListStatus * _Nonnull status) {
        
        
        //移除上拉
        [self.tableView.mj_footer endRefreshing];
        if (status.IsSuccess.integerValue == 1) {
            
            [self.statusArray addObjectsFromArray:status.ResultObj.PageInfo];
            
            [self.tableView reloadData];
            
            
            //预加载
            NSMutableArray *urlArray = [NSMutableArray array];
            for (YWGetNewsDataStatus *dataStatus in status.ResultObj.PageInfo) {
                [urlArray addObject:dataStatus.FileUrl];
            }
            YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
            [playerManager preLoadUrlArray:urlArray];
            
        }
        else{
            
            //它做的接口没数据是走这里的、所以可以直接移除footer
            [self.tableView.mj_footer removeFromSuperview];
            [MBProgressHUD showError:status.Message];
            
        }
        
    } failure:^(NSError * _Nonnull error) {
        
        //移除上拉
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showError:@"服务器繁忙，请稍后再试"];
    }];
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    YWGetNewsDataStatus *status = self.statusArray[indexPath.row];
    
    if (status.cellType == YWCellTypeNoImg || status.cellType == YWCellTypeOneImg) {
      
        
    }
    else if (status.cellType == YWCellTypeVideo){
//            YWVedioController3 *vc = [[YWVedioController3 alloc] initWithNibName:@"YWVedioController3" bundle:nil];
//            vc.status = status;
//            [self.navigationController pushViewController:vc animated:YES];
    }
    else if (status.cellType == YWCellTypeLittleVideo){
//        YWLittleVideoController2 *vc = [[YWLittleVideoController2 alloc] initWithNibName:@"YWLittleVideoController2" bundle:nil];
//        vc.status = status;
//        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
    
}



-(void)listCell:(id)listCell didClickContentWithDataStatus:(YWGetNewsDataStatus *)status{
    if (status.cellType == YWCellTypeNoImg || status.cellType == YWCellTypeOneImg) {
     
    }
    else if (status.cellType == YWCellTypeVideo){
//        YWVedioController3 *vc = [[YWVedioController3 alloc] initWithNibName:@"YWVedioController3" bundle:nil];
//        vc.status = status;
//        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (status.cellType == YWCellTypeLittleVideo){
//        YWLittleVideoController2 *vc = [[YWLittleVideoController2 alloc] initWithNibName:@"YWLittleVideoController2" bundle:nil];
//        vc.status = status;
//        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.statusArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YWGetNewsDataStatus *status = self.statusArray[indexPath.row];
    
    if (status.cellType == YWCellTypeNoImg) {
        
        YWHomeInfoCell *cell = [YWHomeInfoCell cellWithTableView:tableView];
        
        cell.status = status;
        cell.delegate = self;
        
         return cell;
    }
    else if (status.cellType == YWCellTypeOneImg){
        
        YWHomeInfoCell *cell = [YWHomeInfoCell cellWithTableView:tableView];
        
        cell.status = status;
        cell.delegate = self;
        
         return cell;
        
    }
    else if (status.cellType == YWCellTypeVideo){
        
        YWHomeRecommendVedioCell *cell = [YWHomeRecommendVedioCell cellWithTableView:tableView];
        
        cell.status = status;
        cell.delegate = self;
        
         return cell;
        
    }
    else{
        
        YWHomeRecommendLittleVedioCell *cell = [YWHomeRecommendLittleVedioCell cellWithTableView:tableView];
        cell.status = status;
        cell.delegate = self;
        
        return cell;
        
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    tableView.rowHeight = UITableViewAutomaticDimension;

    tableView.estimatedRowHeight = 416;

    return tableView.rowHeight;
    
}






//截取部分高清图（这个不行的截图不了播放器SDK画面、只能用系统的）
-(UIImage*)imageByCaptureScreen  {
    
        UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
        
        CGRect rect = CGRectMake(0 , 0 , Wi , He);
        
        //UIGraphicsBeginImageContext(rect.size);//（ps:截图太模糊）
        
        /*
         
         UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
         
         opaque 透明度，不透明设为YES；
         
         scale  缩放因子，设0时系统自动设置缩放比例图片清晰；设1.0时模糊
         
         */
    
        UIGraphicsBeginImageContextWithOptions(rect.size,YES, 0.0);
        
        CGContextRef context =UIGraphicsGetCurrentContext();
        
        [keyWindow.layer renderInContext:context];
        
        UIImage *img =UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
    
//        CGRect rect1 =CGRectMake(0 , 0 , Wi , CGRectGetMaxY(self.navBar.frame));
//
//        UIImage * imgeee = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([img CGImage], rect1)];
//
        return img;
     
}





@end
